package com.hxg.bl.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxg.bl.bean.AppointmentConfBean;
import com.hxg.bl.bean.AppointmentPeriodTimeBean;
import com.hxg.bl.dao.jpa.AppointmentConfBeanJpa;
import com.hxg.bl.dao.jpa.AppointmentPeriodTimeBeanJpa;
import com.hxg.bl.dao.mapper.AppointmentConfMapper;
import com.hxg.bl.service.AppointmentConfService;
import com.hxg.bl.vo.SearchVo;
import com.hxg.common.LayuiPageInfo;
import com.hxg.common.service.CommonService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Transactional
@Service("appointmentConfService")
public class AppointmentConfServiceImpl implements AppointmentConfService {

    @Autowired
    private AppointmentConfBeanJpa appointmentConfBeanJpa;

    @Autowired
    private AppointmentPeriodTimeBeanJpa appointmentPeriodTimeBeanJpa;

    @Autowired
    private AppointmentConfMapper appointmentConfMapper;

    @Autowired
    private CommonService commonService;

    @Override
    public void saveAndFlushAppointmentConf(AppointmentConfBean appointmentConfBean) {
        if (appointmentConfBean.getId() == null) {
            appointmentConfBean.setOrderNum(appointmentConfBean.getOrderNum() - 1);
            appointmentConfBeanJpa.saveAndFlush(appointmentConfBean);
        }

        String tableName = "cm_appointment_conf";
        commonService.dealOrderNum(appointmentConfBean,
                appointmentConfBeanJpa.getOne(appointmentConfBean.getId()),
                tableName);
        appointmentConfBeanJpa.saveAndFlush(appointmentConfBean);
        commonService.reSortOrderNum(tableName);
        appointmentPeriodTimeBeanJpa.deleteAllByAppointmentConfIdIsNull();
    }

    @Override
    public PageInfo<AppointmentConfBean> listAppointmentConfByParams(Integer pn, Integer pageSize
            , SearchVo searchVo) {
        PageHelper.startPage(pn, pageSize);

        List<AppointmentConfBean> appointmentConfBeanList =
                appointmentConfMapper.listAppointmentConfByParams(searchVo);

        return new LayuiPageInfo<>(appointmentConfBeanList);
    }

    @Override
    public void batchDelAppointmentConf(List<Long> idList) {
        appointmentConfMapper.batchDelAppointmentConf(idList);
        String tableName = "cm_appointment_conf";
        commonService.reSortOrderNum(tableName);
    }

    @Override
    public List<Map<String, Object>> getTimeRangeByIdList(String idList) {
        if (StringUtils.isEmpty(idList)) {
            return new ArrayList<>();
        }
        return appointmentConfMapper.getTimeRangeByIdList(Arrays.asList(idList.split(",")));
    }
}
